import hashlib
import os
import sys
from bs4 import BeautifulSoup

def get_file_md5(file_path):
    """计算文件的 MD5 哈希值"""
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

def add_version_to_links_and_scripts(html_file):
    """读取 HTML 文件并修改 <link> 和 <script> 标签，添加 version 查询参数"""
    with open(html_file, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'html.parser')

    # 找到所有的 <link> 标签
    for link in soup.find_all('link', href=True):
        href = link['href']
        if href.startswith('static/'):
            file_path = os.path.join('.', href)  # 构建文件路径
            if os.path.exists(file_path):
                md5_hash = get_file_md5(file_path)
                link['href'] = f"{href}?version={md5_hash}"

    # 找到所有的 <script> 标签
    for script in soup.find_all('script', src=True):
        src = script['src']
        if src.startswith('static/'):
            file_path = os.path.join('.', src)  # 构建文件路径
            if os.path.exists(file_path):
                md5_hash = get_file_md5(file_path)
                script['src'] = f"{src}?version={md5_hash}"

    # 将修改后的 HTML 写回文件
    with open(html_file, 'w', encoding='utf-8') as f:
        f.write(str(soup))

if __name__ == '__main__':
    # 从命令行参数获取 HTML 文件路径
    if len(sys.argv) != 2:
        print("Usage: python script.py <html_file_path>")
        sys.exit(1)
    # html_file = r'.\static\index.html'

    html_file = sys.argv[1]
    add_version_to_links_and_scripts(html_file)
